package com.bwie.orders.consumer;

import com.alibaba.fastjson2.JSONObject;
import com.bwie.common.core.utils.StringUtils;
import com.bwie.common.redis.service.RedisService;
import com.bwie.common.security.utils.SecurityUtils;
import com.bwie.orders.domain.OrderMessage;
import com.bwie.orders.mapper.OrderMapper;
import com.bwie.system.api.model.LoginUser;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Component
public class OrderConsumer {
    @Autowired
    private OrderMapper mapper;
    @Autowired
    private RedisService redisService;

    // 使用@RabbitListener监听名为order_queue的队列
    @Transactional
    @RabbitListener(queues = "order_queue")
    public void processOrder(OrderMessage message) {


        //添加订单表
        mapper.orderAdd(message.getOrderNum(), message.getUserId(), message.getTotalPrice());
        //添加订单sku中间表
        message.getSkus().forEach(sku -> mapper.addOrderSku(message.getOrderNum(), sku));

        //获取登录用户
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        if(StringUtils.isNull(loginUser)){
//         return;
//        }
//        Long userid = loginUser.getUserid();
        System.out.println("有没有走到这一步");
        //redis添加订单状态
        redisService.setCacheObject("DD:"+message, JSONObject.toJSONString(message), 10L, TimeUnit.HOURS);
    }

}
